﻿<%@ WebHandler Language="C#" Class="DataDictionaryMgr" %>

using System;
using System.Web;
using Chenxin.Lib.Utility;
using System.Data;
using System.Text;
using System.Collections.Generic;

public class DataDictionaryMgr : AjaxHandlerBase
{
    public DataDictionaryMgr()
    {
        htTypePermit.Add("add", Constants.Permit_DicItem_Add);
        htTypePermit.Add("del", Constants.Permit_DicItem_Del);
        htTypePermit.Add("edit", Constants.Permit_DicItem_Edit);
    }

    override public void RequestProcess(HttpContext context)
    {
        context.Response.AddHeader("pragma", "no-cache");
        context.Response.AddHeader("cache-control", "");
        context.Response.CacheControl = "no-cache";
        
        switch (context.Request["op"].ToLower())
        {
            case "getlist":
                GetList(context);
                break;
            case "getdataitemcombolist":
                GetDataItemComboList(context);
                break;
            case "add":
                Add(context);
                break;
            case "del":
                Del(context);
                break;
            case "edit":
                Edit(context);
                break;
            case "getitemindex":
                GetItemIndex(context);
                break;
        }
    }

    public void GetItemIndex(HttpContext context)
    {
        try
        {
            if (context.Request["region"] != null)
            {
                int index = Chenxin.Lib.House.DAL.DataDictionary.GetBlockItemIndex(Convert.ToInt32(context.Request["region"]));

                context.Response.Write("{success:1,msg:'',data:{ItemIndex:" + index + "}}");
            }
            else
            {
                context.Response.Write("{success:0,msg:'获取失败',data:''}");
            }
        }
        catch
        {
            context.Response.Write("{success:0,msg:'获取失败！',data:''}");
        }
    }

    public void Add(HttpContext context)
    {
        try
        {
            Chenxin.Lib.House.Entity.DataDictionary model = (Chenxin.Lib.House.Entity.DataDictionary)JsonHelp.Convert2Entity(context.Request["model"], typeof(Chenxin.Lib.House.Entity.DataDictionary));

            model.RecordId = Guid.NewGuid();
            if (model.ItemKey == "System.Block")
            {
                model.ItemIndex = Chenxin.Lib.House.DAL.DataDictionary.GetBlockItemIndex(Convert.ToInt32(context.Request["region"]));
            }  
            Chenxin.Lib.House.DAL.DataDictionary.Add(model);

            //删除
            Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.DICTDATA);

            cs.Delete(string.Format(Chenxin.Lib.Cache.CacheDataType.DICTDATA, model.ItemKey + "." + model.CompanyId.ToString()));
            cs.Delete(string.Format(Chenxin.Lib.Cache.CacheDataType.DICTDATA, model.ItemKey + "." + model.CityId.ToString()));
          

            //添加用户操作日志 2010-5-11 王玮 Add
            AddLog("" + CurrentUserInfo.UserName + "添加了一个数据字典参数:标识值为[" + model.ItemKey + "]的[" + model.ItemValue + "]",
                    OperationType.OperationTypeComboList()["OprType_DataDictionaryAdd"].ToString());
            
            context.Response.Write("{success:1,msg:'添加成功！',data:'" + model.RecordId + "'}");
        }
        catch(Exception e)
        {
            context.Response.Write("{success:0,msg:'"+e.Message+"',data:''}");                
        }
        
        
    }

    /// <summary>
    /// 删除
    /// </summary>
    /// <param name="context"></param>
    public void Del(HttpContext context)
    {
        try
        {
            if (context.Request["modelid"] != null)
            {
                Chenxin.Lib.House.Entity.DataDictionary model = Chenxin.Lib.House.DAL.DataDictionary.GetModel(new Guid(context.Request["modelid"]));

                if (model != null)
                {
                    Chenxin.Lib.House.DAL.DataDictionary.Delete(new Guid(context.Request["modelid"]));

                    //删除
                    Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.DICTDATA);
                    cs.Delete(string.Format(Chenxin.Lib.Cache.CacheDataType.DICTDATA, model.ItemKey + "." + model.CompanyId.ToString()));
                    cs.Delete(string.Format(Chenxin.Lib.Cache.CacheDataType.DICTDATA, model.ItemKey + "." + model.CityId.ToString()));

                    //添加用户操作日志 2010-5-11 王玮 Add
                    AddLog("" + CurrentUserInfo.UserName + "删除了一个数据字典参数:标识值为[" + model.ItemKey + "]的[" + model.ItemValue + "]",
                            OperationType.OperationTypeComboList()["OprType_DataDictionaryDel"].ToString());
                    
                    context.Response.Write("{success:'1',msg:'删除成功！',data:''}");
                }
                else
                {

                    context.Response.Write("{success:'0',msg:'删除失败！',data:''}");
                }
            }
            else
            {
                context.Response.Write("{success:'0',msg:'删除失败,请选择一条记录！',data:''}");
            }
        }
        catch
        {
            context.Response.Write("{success:'0',msg:'删除失败！',data:''}");
        }
    }

    public void Edit(HttpContext context)
    {
        try
        {
            Chenxin.Lib.House.Entity.DataDictionary model = (Chenxin.Lib.House.Entity.DataDictionary)JsonHelp.Convert2Entity(context.Request["model"], typeof(Chenxin.Lib.House.Entity.DataDictionary));

            Chenxin.Lib.House.DAL.DataDictionary.Update(model);
            model.RecordId = Guid.NewGuid();





            //删除
            Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.DICTDATA);
            cs.Delete(string.Format(Chenxin.Lib.Cache.CacheDataType.DICTDATA, model.ItemKey + "." + CurrentUserInfo.CompanyId.ToString()));
            cs.Delete(string.Format(Chenxin.Lib.Cache.CacheDataType.DICTDATA, model.ItemKey + "." + CurrentUserInfo.CityId.ToString()));
            

            //添加用户操作日志 2010-5-11 王玮 Add
            AddLog("" + CurrentUserInfo.UserName + "编辑了一个数据字典参数:标识值为[" + model.ItemKey + "]的[" + model.ItemValue + "]",
                    OperationType.OperationTypeComboList()["OprType_DataDictionaryEdit"].ToString());
            
            context.Response.Write("{success:1,msg:'编辑成功！',data:'" + model.RecordId + "'}");
        }
        catch
        {
            context.Response.Write("{success:0,msg:'编辑失败！',data:''}");
        }        
        
    }

    public void GetList(HttpContext context)
    {
        try
        {
            string where = "";
            string order = "ItemKey,ItemIndex desc";

            int pageSize = 10;
            int pageIndex = 1;
            int count = 0;

            //判断查询权限
            if (CurrentUserInfo.ContainsPermit(Constants.Permit_DicItem_All))
            {
                where=" 1=1 ";
            }
            //城市
            else if (CurrentUserInfo.ContainsPermit(Constants.Permit_DicItem_City))
            {
                where = " cityid='"+CurrentUserInfo.CityId.ToString()+"' ";
            }
            //公司
            else if (CurrentUserInfo.ContainsPermit(Constants.Permit_DicItem_Company))
            {
                where = " companyid='"+CurrentUserInfo.CompanyId.ToString()+"' ";
            }
            //没有权限
            else
            {
                where = " 1=0 ";
            }
            
            if (context.Request["itemkey"] != null)
            {
                where += string.Format(" and ItemKey='{0}'", context.Request["itemkey"]);
            }

            if (context.Request["cityid"] != null)
            {
                where += string.Format(" and cityid='{0}'", context.Request["cityid"]);
            }
            else
            {
                where += string.Format(" and cityid='{0}'", CurrentUserInfo.CityId);
            }

            if (context.Request["companyid"] != null)
            {
                where += string.Format(" and (companyid='{0}' or company is null)", context.Request["companyid"]);
            }
            else
            {
                if (context.Request["cityid"] == null)//选过城市，没有选择公司，则不添加当前人所在公司的默认
                {
                    where += string.Format(" and (companyid='{0}' or company is null)", CurrentUserInfo.CompanyId);
                }
            }
            
            if (context.Request["pagesize"] != null)
            {
                pageSize = Convert.ToInt32(context.Request["pagesize"]);
            }
            if (context.Request["pageindex"] != null)
            {
                pageIndex = Convert.ToInt32(context.Request["pageindex"]) + 1;
            }

            DataSet ds = Chenxin.Lib.House.DAL.DataDictionary.GetList("*", where, order, pageIndex, pageSize, true);

            if (ds.Tables.Count == 2)
            {
                count = Convert.ToInt32(ds.Tables[1].Rows[0].ItemArray[0]);

                context.Response.Write(string.Format("{{success:'1',data:{{data:'{0}',count:{1}}}}}", CreateGrid(ds.Tables[0].Select("1=1")), count));
            }
            else
            {
                context.Response.Write("{success,'0',msg:'加载失败！',data:''}");
            }
        }
        catch (Exception e)
        {
            context.Response.Write("{success,'0',msg:'加载失败！',data:''}");
        }
    }

    /// <summary>
    /// 生成列表
    /// </summary>
    /// <param name="drList"></param>
    /// <returns></returns>
    public string CreateGrid(DataRow[] drList)
    {
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        sb.Append("<table style=\"width:100%\" cellspacing=\"1\" class=\"tabsorternew\" id=\"report\">");
        sb.Append("<thead><tr>");
        //sb.Append("<th width=\"20px\"></th>");
        sb.Append("<th width=\"120px\" >标识名</th>");
        sb.Append("<th width=\"120px\" >标识值</th>");
        sb.Append("<th>值</th>");
        sb.Append("<th width=\"60px\">类型</th>");
        sb.Append("<th width=\"60px\">排序</th>");
        sb.Append("<th width=\"80px\">城市</th>");
        sb.Append("<th width=\"80px\">公司</th>");
        sb.Append("</tr></thead>");
        sb.Append("<tbody>");

        foreach (DataRow dr in drList)
        {
            sb.AppendFormat("<tr id=\"{0}\" class=\"tr_datadictionary\">", dr["RecordId"]);
            //sb.AppendFormat("<td><input value=\"{0}\" name=\"input_chk\" type=\"checkbox\"/></td>", dr["RecordId"]);

            sb.AppendFormat("<td>{0}</td>", dr["ItemRemark"]);
            sb.AppendFormat("<td>{0}</td>", dr["ItemKey"]);
            sb.AppendFormat("<td>{0}</td>", dr["ItemValue"]);
            sb.AppendFormat("<td>{0}</td>", dr["ItemType"]);
            sb.AppendFormat("<td>{0}</td>", dr["ItemIndex"]);
            sb.AppendFormat("<td>{0}</td>", dr["City"]);
            sb.AppendFormat("<td>{0}</td>", dr["Company"]);
            sb.Append("</tr>");
        }
        sb.Append("</tbody>");
        sb.Append("</table>");

        return sb.ToString();
    }

    /// <summary>
    /// 获取类型Combo
    /// </summary>
    /// <param name="context"></param>
    public void GetDataItemComboList(HttpContext context)
    {
        try
        {
            Chenxin.Lib.House.BLL.DataDictionaryItem bll = new Chenxin.Lib.House.BLL.DataDictionaryItem();

            StringBuilder shortListSb = new StringBuilder();
            List<Chenxin.Lib.House.Entity.DataDictionaryItem> dataDictionaryItemList = bll.GetModelList("", "");

            foreach (Chenxin.Lib.House.Entity.DataDictionaryItem tempItem in dataDictionaryItemList)
            {
                shortListSb.Append("{");
                shortListSb.AppendFormat("txt:'{0}',val:'{1}'", tempItem.ItemRemark, tempItem.ItemKey);
                shortListSb.Append("},");
            }

            if (shortListSb.Length > 0)
            {
                shortListSb.Remove(shortListSb.Length - 1, 1);
            }
            context.Response.Write(string.Format("{{success:'1',msg:'成功',data:{{items:[{0}]}}}}", shortListSb.ToString()));
        }
        catch
        {
            context.Response.Write("{success:0,msg:'加载失败！',data:{items:[]}}");        
        }
    }

}